"""
The driver is based on devbis' st7789py_mpy module from
https://github.com/devbis/st7789py_mpy.

This driver adds support for:

- 320x240, 240x240 and 135x240 pixel displays
- Display rotation
- Hardware based scrolling
- Drawing text using 8 and 16 bit wide bitmap fonts with heights that are
  multiples of 8.  Included are 12 bitmap fonts derived from classic pc
  BIOS text mode fonts.
- Drawing text using converted TrueType fonts.
- Drawing converted bitmaps

"""
'''
导入字体
'''

import time
from micropython import const
import ustruct as struct



# commands
ST7789_NOP = const(0x00)
ST7789_SWRESET = const(0x01)
ST7789_RDDID = const(0x04)
ST7789_RDDST = const(0x09)

ST7789_SLPIN = const(0x10)
ST7789_SLPOUT = const(0x11)
ST7789_PTLON = const(0x12)
ST7789_NORON = const(0x13)

ST7789_INVOFF = const(0x20)
ST7789_INVON = const(0x21)
ST7789_DISPOFF = const(0x28)
ST7789_DISPON = const(0x29)
ST7789_CASET = const(0x2A)
ST7789_RASET = const(0x2B)
ST7789_RAMWR = const(0x2C)
ST7789_RAMRD = const(0x2E)

ST7789_PTLAR = const(0x30)
ST7789_VSCRDEF = const(0x33)
ST7789_COLMOD = const(0x3A)
ST7789_MADCTL = const(0x36)
ST7789_VSCSAD = const(0x37)

ST7789_MADCTL_MY = const(0x80)  # D7
ST7789_MADCTL_MX = const(0x40)  # D6
ST7789_MADCTL_MV = const(0x20)  # D5
ST7789_MADCTL_ML = const(0x10)  # D4
ST7789_MADCTL_BGR = const(0x08)  # D3
ST7789_MADCTL_MH = const(0x04)  # D2
ST7789_MADCTL_RGB = const(0x00)  # D0

ST7789_RDID1 = const(0xDA)
ST7789_RDID2 = const(0xDB)
ST7789_RDID3 = const(0xDC)
ST7789_RDID4 = const(0xDD)

COLOR_MODE_65K = const(0x50)
COLOR_MODE_262K = const(0x60)
COLOR_MODE_12BIT = const(0x03)
COLOR_MODE_16BIT = const(0x05)
COLOR_MODE_18BIT = const(0x06)
COLOR_MODE_16M = const(0x07)

# color order
RGB = 0x00
BGR = 0x08

# Color definitions
BLACK = const(0x0000)
BLUE = const(0x001F)
RED = const(0xF800)
GREEN = const(0x07E0)
CYAN = const(0x07FF)
MAGENTA = const(0xF81F)
YELLOW = const(0xFFE0)
WHITE = const(0xFFFF)

# _ENCODE_PIXEL = ">H"
# _ENCODE_POS = ">HH"
# _DECODE_PIXEL = ">BBB"

_BUFFER_SIZE = const(256)

# _BIT7 = const(0x80)
# _BIT6 = const(0x40)
# _BIT5 = const(0x20)
# _BIT4 = const(0x10)
# _BIT3 = const(0x08)
# _BIT2 = const(0x04)
# _BIT1 = const(0x02)
# _BIT0 = const(0x01)
# _BIT = [_BIT0, _BIT1, _BIT2, _BIT3, _BIT4, _BIT5, _BIT6, _BIT7]
# Rotation tables (width, height, xstart, ystart)[rotation % 4]

WIDTH_320 = [(240, 320, 0, 0), (320, 240, 0, 0), (240, 320, 0, 0), (320, 240, 0, 0)]

WIDTH_240 = [(240, 240, 0, 0), (240, 240, 0, 0), (240, 240, 0, 80), (240, 240, 80, 0)]

WIDTH_135 = [(135, 240, 52, 40), (240, 135, 40, 53), (135, 240, 53, 40), (240, 135, 40, 52)]

# MADCTL ROTATIONS[rotation % 4]
# ROTATIONS = [0x00, 0x60, 0xc0, 0xa0]
ROTATIONS = [0x40, 0xe0, 0x80, 0x20]  # 修正镜像显示问题

# 屏幕显示辅助类，用于显示文字和图片
from tft.displayer import  *





class ST7789():
    """
    ST7789驱动类

    参数:
        spi (spi): SPI对象 **必需**
        width (int): 显示宽度 **必需**
        height (int): 显示高度 **必需**
        reset (pin): 复位引脚
        dc (pin): 数据/命令引脚 **必需**
        cs (pin): 片选引脚
        backlight (pin): 背光引脚
        rotation (int): 显示旋转方向
            - 0-竖屏
            - 1-横屏
            - 2-倒置竖屏
            - 3-倒置横屏
    """

    def __init__(self, spi=None, width=240, height=320, reset=None, dc=None, cs=None, backlight=None, rotation=0,
                 color_order=BGR):
        """
        初始化显示屏。

        :param spi: 用于通信的SPI接口。
        :param width: 显示屏宽度。
        :param height: 显示屏高度。
        :param reset: 复位引脚。
        :param dc: 数据/命令引脚。
        :param cs: 片选引脚。
        :param backlight: 背光控制引脚。
        :param rotation: 屏幕旋转角度。
        :param color_order: 颜色顺序，默认为BGR。
        :raises ValueError: 如果显示屏尺寸不受支持或缺少必要的引脚。
        """
        # 检查是否支持的显示屏尺寸
        if height != 240 or width not in [320, 240, 135]:
            raise ValueError("不支持的显示屏。支持的尺寸为：320x240、240x240 和 135x240。")

        # 确保提供了dc引脚
        if dc is None:
            raise ValueError("必须提供dc引脚。")

        # 初始化显示屏尺寸
        self._display_width = self.width = width
        self._display_height = self.height = height
        self.xstart = 0
        self.ystart = 0
        self.spi = spi
        self.reset = reset
        self.dc = dc
        self.cs = cs
        self.backlight = backlight
        self._rotation = rotation % 4
        self.color_order = color_order

        # 初始化引脚
        # self.hard_reset()
        # self.soft_reset()
        if self.cs is not None:
            self.cs.init(self.cs.OUT, value=1)

        if self.dc is not None:
            self.dc.init(self.dc.OUT, value=0)

        if self.reset is not None:
            self.reset.init(self.reset.OUT, value=1)

        # 配置显示屏设置
        self.sleep_mode(False)

        self._set_color_mode(COLOR_MODE_65K | COLOR_MODE_16BIT)
        time.sleep_ms(50)

        self.inversion_mode(False)
        time.sleep_ms(10)

        self.rotation(self._rotation)
        time.sleep_ms(50)

        self._write(ST7789_NORON)
        time.sleep_ms(10)
        if backlight is not None:
            # backlight.value(1)
            self.backlight.init(self.backlight.OUT, value=1)

        self._write(ST7789_DISPON)
        time.sleep_ms(500)
        # self.fill(0)
        self.fill(BLACK)

        # 初始化图片显示器
        self.image_displayer = ImageDisplayer(self)
        self.text_displayer = TextDisplayer(self)

    def _write(self, command=None, data=None):
        """SPI write to the device: commands and data."""
        if self.cs:
            self.cs.off()

        if command is not None:
            self.dc.off()
            self.spi.write(bytes([command]))
        if data is not None:
            self.dc.on()
            self.spi.write(data)
            if self.cs:
                self.cs.on()

    def hard_reset(self):
        """
        Hard reset display.
        """
        if self.cs:
            self.cs.off()
        if self.reset:
            self.reset.on()
        time.sleep_ms(50)
        if self.reset:
            self.reset.off()
        time.sleep_ms(50)
        if self.reset:
            self.reset.on()
        time.sleep_ms(150)
        if self.cs:
            self.cs.on()

    def soft_reset(self):
        """
        Soft reset display.
        """
        self._write(ST7789_SWRESET)
        time.sleep_ms(150)

    def sleep_mode(self, value):
        """
        Enable or disable display sleep mode.

        Args:
            value (bool): if True enable sleep mode. if False disable sleep
            mode
        """
        if value:
            self._write(ST7789_SLPIN)
        else:
            self._write(ST7789_SLPOUT)

    def inversion_mode(self, value):
        """
        启用或禁用显示反转模式。

        参数:
            value (bool): 如果为True，则启用反转模式；如果为False，则禁用反转模式。
        """
        if value:
            self._write(ST7789_INVON)
        else:
            self._write(ST7789_INVOFF)

    def _set_color_mode(self, mode):
        """
        Set display color mode.

        Args:
            mode (int): color mode
                COLOR_MODE_65K, COLOR_MODE_262K, COLOR_MODE_12BIT,
                COLOR_MODE_16BIT, COLOR_MODE_18BIT, COLOR_MODE_16M
        """
        self._write(ST7789_COLMOD, bytes([mode & 0x77]))

    def rotation(self, rotation):
        """
        设置显示旋转方向。

        参数:
            rotation (int):
                - 0-竖屏
                - 1-横屏
                - 2-倒置竖屏
                - 3-倒置横屏
        """

        rotation %= 4
        self._rotation = rotation
        madctl = ROTATIONS[rotation]

        if self._display_width == 320:
            table = WIDTH_320
        elif self._display_width == 240:
            table = WIDTH_240
        elif self._display_width == 135:
            table = WIDTH_135
        else:
            raise ValueError("Unsupported display. 320x240, 240x240 and 135x240 are supported.")

        self.width, self.height, self.xstart, self.ystart = table[rotation]
        # self._write(ST7789_MADCTL, bytes([madctl]))
        # 增加颜色顺序支持
        if self.color_order == BGR:
            madctl |= ST7789_MADCTL_BGR
        else:
            madctl &= ~ST7789_MADCTL_BGR

        self._write(ST7789_MADCTL, bytes([madctl]))

    def _set_columns(self, start, end):
        """
        Send CASET (column address set) command to display.

        Args:
            start (int): column start address
            end (int): column end address
        """
        if start <= end <= self.width:
            self._write(ST7789_CASET, encode_pos(start + self.xstart, end + self.xstart))

    def _set_rows(self, start, end):
        """
        Send RASET (row address set) command to display.

        Args:
            start (int): row start address
            end (int): row end address
       """
        if start <= end <= self.height:
            self._write(ST7789_RASET, encode_pos(start + self.ystart, end + self.ystart))

    def _set_window(self, x0, y0, x1, y1):
        """
        Set window to column and row address.

        Args:
            x0 (int): column start address
            y0 (int): row start address
            x1 (int): column end address
            y1 (int): row end address
        """
        self._set_columns(x0, x1)
        self._set_rows(y0, y1)
        self._write(ST7789_RAMWR)

    def vline(self, x, y, length, color):
        """
        Draw vertical line at the given location and color.

        Args:
            x (int): x coordinate
            Y (int): y coordinate
            length (int): length of line
            color (int): 565 encoded color
        """
        self.fill_rect(x, y, 1, length, color)

    def hline(self, x, y, length, color):
        """
        Draw horizontal line at the given location and color.

        Args:
            x (int): x coordinate
            Y (int): y coordinate
            length (int): length of line
            color (int): 565 encoded color
        """
        self.fill_rect(x, y, length, 1, color)

    def pixel(self, x, y, color):
        """
        Draw a pixel at the given location and color.

        Args:
            x (int): x coordinate
            Y (int): y coordinate
            color (int): 565 encoded color
        """
        self._set_window(x, y, x, y)
        self._write(None, encode_pixel(color))

    def blit_buffer(self, buffer, x, y, width, height):
        """
        Copy buffer to display at the given location.

        Args:
            buffer (bytes): Data to copy to display
            x (int): Top left corner x coordinate
            Y (int): Top left corner y coordinate
            width (int): Width
            height (int): Height
        """
        self._set_window(x, y, x + width - 1, y + height - 1)
        self._write(None, buffer)

    def rect(self, x, y, w, h, color):
        """
        Draw a rectangle at the given location, size and color.

        Args:
            x (int): Top left corner x coordinate
            y (int): Top left corner y coordinate
            width (int): Width in pixels
            height (int): Height in pixels
            color (int): 565 encoded color
        """
        self.hline(x, y, w, color)
        self.vline(x, y, h, color)
        self.vline(x + w - 1, y, h, color)
        self.hline(x, y + h - 1, w, color)

    def fill_rect(self, x, y, width, height, color):
        """
        Draw a rectangle at the given location, size and filled with color.

        Args:
            x (int): Top left corner x coordinate
            y (int): Top left corner y coordinate
            width (int): Width in pixels
            height (int): Height in pixels
            color (int): 565 encoded color
        """
        self._set_window(x, y, x + width - 1, y + height - 1)
        chunks, rest = divmod(width * height, _BUFFER_SIZE)
        pixel = encode_pixel(color)
        self.dc.on()
        if chunks:
            data = pixel * _BUFFER_SIZE
            for _ in range(chunks):
                self._write(None, data)
        if rest:
            self._write(None, pixel * rest)

    def fill(self, color):
        """
        Fill the entire FrameBuffer with the specified color.

        Args:
            color (int): 565 encoded color
        """
        self.fill_rect(0, 0, self.width, self.height, color)

    def line(self, x0, y0, x1, y1, color):
        """
        Draw a single pixel wide line starting at x0, y0 and ending at x1, y1.

        Args:
            x0 (int): Start point x coordinate
            y0 (int): Start point y coordinate
            x1 (int): End point x coordinate
            y1 (int): End point y coordinate
            color (int): 565 encoded color
        """
        steep = abs(y1 - y0) > abs(x1 - x0)
        if steep:
            x0, y0 = y0, x0
            x1, y1 = y1, x1
        if x0 > x1:
            x0, x1 = x1, x0
            y0, y1 = y1, y0
        dx = x1 - x0
        dy = abs(y1 - y0)
        err = dx // 2
        ystep = 1 if y0 < y1 else -1
        while x0 <= x1:
            if steep:
                self.pixel(y0, x0, color)
            else:
                self.pixel(x0, y0, color)
            err -= dy
            if err < 0:
                y0 += ystep
                err += dx
            x0 += 1

    def vscrdef(self, tfa, vsa, bfa):
        """
        设置垂直滚动定义。

        对于一个135x240的显示屏，这些值应为40, 240, 40。
        屏幕上方有40行未显示，接着是240行显示内容，最后再跟40行未显示。
        你可以写入这些未显示区域，并通过更改TFA、VSA和BFA值将它们滚动到视图中。

        参数:
            tfa (int): 顶部固定区域
            vsa (int): 垂直滚动区域
            bfa (int): 底部固定区域
        """
        struct.pack(">HHH", tfa, vsa, bfa)
        self._write(ST7789_VSCRDEF, struct.pack(">HHH", tfa, vsa, bfa))

    def vscsad(self, vssa):
        """
        Set Vertical Scroll Start Address of RAM.

        Defines which line in the Frame Memory will be written as the first
        line after the last line of the Top Fixed Area on the display

        Example:

            for line in range(40, 280, 1):
                tft.vscsad(line)
                utime.sleep(0.01)

        Args:
            vssa (int): Vertical Scrolling Start Address

        """
        self._write(ST7789_VSCSAD, struct.pack(">H", vssa))


    def text(self, size=16, text=None, x0=0, y0=0, color=WHITE, background=BLACK):
        """
        Draw text on display in specified font and colors. 8 and 16 bit wide
        fonts are supported.

        Args:
            size : 中文支持16,24,32,48；英文默认使用16号字体，支持8、16种字号.
            text (str): text to write
            x0 (int): column to start drawing at
            y0 (int): row to start drawing at
            color (int): 565 encoded color to use for characters
            background (int): 565 encoded color to use for background
        """
        if not size in [8, 16, 24, 32, 48]:
            print(f"不支持{size}号大小的字体。")
            size = 16

        self.text_displayer.text(size, text, x0, y0, color, background)



    def display_bmp(self, file_path, x, y):
        """
        在 TFT 显示屏上显示 BMP 图像。

        参数:
            file_path (str): BMP 文件的路径。
            x (int): 图像显示的起始 x 坐标。
            y (int): 图像显示的起始 y 坐标。
        """
        self.image_displayer.display_bmp(file_path, x, y)

    def bitmap(self, bitmap, x, y, index=0):
        """
        在指定的列和行绘制位图。

        参数:
            bitmap (bitmap_module): 包含要绘制的位图的模块
            x (int): 开始绘制的列
            y (int): 开始绘制的行
            index (int): 可选参数，从多个位图模块中选择要绘制的位图索引

        """
        bitmap_size = bitmap.HEIGHT * bitmap.WIDTH
        buffer_len = bitmap_size * 2
        buffer = bytearray(buffer_len)
        bs_bit = bitmap.BPP * bitmap_size * index if index > 0 else 0

        for i in range(0, buffer_len, 2):
            color_index = 0
            for _ in range(bitmap.BPP):
                color_index <<= 1
                color_index |= (bitmap.BITMAP[bs_bit // 8] & 1 << (7 - (bs_bit % 8))) > 0
                bs_bit += 1

            color = bitmap.PALETTE[color_index]
            buffer[i] = color & 0xff00 >> 8
            buffer[i + 1] = color_index & 0xff

        to_col = x + bitmap.WIDTH - 1
        to_row = y + bitmap.HEIGHT - 1
        if self.width > to_col and self.height > to_row:
            self._set_window(x, y, to_col, to_row)
            self._write(None, buffer)

    # @micropython.native
    def write(self, font, string, x, y, fg=WHITE, bg=BLACK):
        """
        使用转换后的 TrueType 字体在显示屏上从指定的列和行开始写入字符串。

        参数:
            font (font): 包含转换后的 TrueType 字体的模块
            s (string): 要写入的字符串
            x (int): 开始写入的列
            y (int): 开始写入的行
            fg (int): 前景色，默认为白色
            bg (int): 背景色，默认为黑色
        """
        buffer_len = font.HEIGHT * font.MAX_WIDTH * 2
        buffer = bytearray(buffer_len)
        fg_hi = (fg & 0xff00) >> 8
        fg_lo = fg & 0xff

        bg_hi = (bg & 0xff00) >> 8
        bg_lo = bg & 0xff

        for character in string:
            try:
                char_index = font.MAP.index(character)
                offset = char_index * font.OFFSET_WIDTH
                bs_bit = font.OFFSETS[offset]
                if font.OFFSET_WIDTH > 1:
                    bs_bit = (bs_bit << 8) + font.OFFSETS[offset + 1]

                if font.OFFSET_WIDTH > 2:
                    bs_bit = (bs_bit << 8) + font.OFFSETS[offset + 2]

                char_width = font.WIDTHS[char_index]
                buffer_needed = char_width * font.HEIGHT * 2

                for i in range(0, buffer_needed, 2):
                    if font.BITMAPS[bs_bit // 8] & 1 << (7 - (bs_bit % 8)) > 0:
                        buffer[i] = fg_hi
                        buffer[i + 1] = fg_lo
                    else:
                        buffer[i] = bg_hi
                        buffer[i + 1] = bg_lo

                    bs_bit += 1

                to_col = x + char_width - 1
                to_row = y + font.HEIGHT - 1
                if self.width > to_col and self.height > to_row:
                    self._set_window(x, y, to_col, to_row)
                    self._write(None, buffer[:buffer_needed])

                x += char_width

            except ValueError:
                pass

    def write_width(self, font, string):
        """
        返回使用指定字体写入字符串时的像素宽度。

        参数:
            font (font): 包含转换后的 TrueType 字体的模块
            string (string): 要测量的字符串
        """
        width = 0
        for character in string:
            try:
                char_index = font.MAP.index(character)
                width += font.WIDTHS[char_index]

            except ValueError:
                pass

        return width

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.spi.deinit()

